package com.mobiletrain.org.motherkitch.shequ;


import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.media.Image;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.bitmap.PauseOnScrollListener;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.mobiletrain.org.motherkitch.R;
import com.mobiletrain.org.motherkitch.utils.ImageLoad;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.util.ArrayList;
//美食社会
public class ShequFragment extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String mParam1;
    private String mParam2;
    private SheQuClass sheQuClass;
    private ArrayList<SheQuClass> sheQudata;
    private sheQuAdapter adapter;
    private PullToRefreshListView refreshListView;
    private ProgressBar bar;
    private ListView list;
    private int page = 1;
    private int limit = 30;
    private String path = "http://www.qubaobei.com/ios/cf/bbs_list.php?qid=10011&limit="+limit*page;
    private ImageView image;

    public static ShequFragment newInstance(String param1, String param2) {
        ShequFragment fragment = new ShequFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        return fragment;
    }

    public ShequFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_shequ, container, false);

        //上拉加载，下拉刷新
        refreshListView = (PullToRefreshListView) view.findViewById(R.id.refreshListView);
        image = (ImageView) view.findViewById(R.id.image);
        getRefrshListView(view);
        return view;
    }

    private void getRefrshListView(View view) {
        refreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        final ILoadingLayout loadingLayoutProxy = refreshListView.getLoadingLayoutProxy();
        final Drawable icon = getActivity().getResources().getDrawable(R.drawable.xlistview_arrow);
        loadingLayoutProxy.setLoadingDrawable(icon);
        loadingLayoutProxy.setReleaseLabel("放开刷新");
        loadingLayoutProxy.setRefreshingLabel("正在加载...");
        BitmapUtils bitmapUtils = ImageLoad.getBitmapUtils(getActivity());
        refreshListView.setOnScrollListener(new PauseOnScrollListener(bitmapUtils,false,true));
        refreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                loadingLayoutProxy.setPullLabel("下拉刷新");
                String time = DateUtils.formatDateTime(getActivity(), System.currentTimeMillis(), DateUtils.FORMAT_ABBREV_ALL
                        | DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE);
                loadingLayoutProxy.setLastUpdatedLabel("最后更新时间："+time);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refreshListView.onRefreshComplete();
                    }
                },2000);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                loadingLayoutProxy.setPullLabel("上拉加载");
                String time = DateUtils.formatDateTime(getActivity(), System.currentTimeMillis(), DateUtils.FORMAT_ABBREV_ALL
                        | DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE);
                loadingLayoutProxy.setLastUpdatedLabel("最后更新时间："+time);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refreshListView.onRefreshComplete();
                    }
                },2000);


            }

        }

        );
        bar = (ProgressBar) view.findViewById(R.id.progressBar);
        sheQudata =new ArrayList<SheQuClass>();
        adapter = new sheQuAdapter(getActivity(),sheQudata);
        getSheQu();
        refreshListView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                page++;
                getSheQu();
                Toast.makeText(getActivity(), "正在加载...", Toast.LENGTH_LONG).show();
            }
        });
        list = refreshListView.getRefreshableView();
        list.setEmptyView(bar);
        list.setAdapter(adapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                intent.putExtra("id",sheQudata.get(position-1).getId());
                intent.setClass(getActivity(),SheQuActivity.class);
                startActivity(intent);
            }
        });
    }

    private void getSheQu() {

        HttpUtils http = new HttpUtils();
        HttpHandler<String> send = http.send(HttpRequest.HttpMethod.GET, path, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> stringResponseInfo) {
                String json = stringResponseInfo.result.toString();
                try {
                    JSONObject jsonObject = new JSONObject(json);
                    JSONArray data = jsonObject.getJSONArray("data");
                    for (int i = 0; i < data.length(); i++) {
                        JSONObject jsonObject1 = data.getJSONObject(i);
                        String id = jsonObject1.getString("id");
                        String title = jsonObject1.getString("title");
                        String dated = jsonObject1.getString("dated");
                        String showdated = jsonObject1.getString("showdated");
                        String post_type = jsonObject1.getString("post_type");
                        String re_num = jsonObject1.getString("re_num");
                        String pic = jsonObject1.getString("pic");
                        String gold_added = jsonObject1.getString("gold_added");
                        String avatar = jsonObject1.getString("avatar");
                        String nickname = jsonObject1.getString("nickname");
                        String age_str = jsonObject1.getString("age_str");
                        sheQuClass = new SheQuClass(id,title,dated,showdated,post_type,re_num,pic,gold_added,avatar,nickname,age_str);
                        sheQudata.add(sheQuClass);
                    }
                    image.setVisibility(View.INVISIBLE);
                    adapter.notifyDataSetChanged();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Toast.makeText(getActivity(), "下载失败", Toast.LENGTH_SHORT).show();
            }
        });


    }


}
